/*
 * String.cpp
 *
 *  Created on: 31.03.2010
 *      Author: Josa
 */

#include "String.h"

#include <iostream>

using namespace std;

String::String(){
	this->text = new char[0];
	this->laenge = 0;
	this->zwischenspeicher = new char[0];
}

String::String(char *op){
	this->laenge = 0;
	this->zwischenspeicher = new char[0];

	for(int i = 0 ; op[i] != '\0' ; i++){
		this->laenge++;
	}

	this->text = new char[this->laenge+1];
	for(int i = 0; op[i] != '\0' ; i++){
		this->text[i] = op[i];
	}
	this->text[this->laenge]  = '\0';
}
String::String(String &op){

	int index=0;
	this->laenge=0;

	this->laenge = op.laenge;

	this->text = new char[this->laenge+1];
	this->zwischenspeicher = new char[0];

	if(this->laenge>0){

		for(int i = 0 ; op.getText(i) != '\0' ; i++){
			this->text[i] = op.getText(i);
			index = i+1;
		}

		this->text[index] = '\0';
	}
}

char String::getText(int index){
	return this->text[index];
}

String::~String ()
{
	delete[] this->text;
	delete[] this->zwischenspeicher;
	cout<< "geloescht"<<endl;
}

String& String::operator+=(String& op){
	int index = 0;
	delete[] this->zwischenspeicher;
	this->zwischenspeicher = new char[(this->laenge + op.laenge)];

	for(int i = 0 ; i < this->laenge ; i++)
	{
		this->zwischenspeicher[i] = this->text[i];
	}
	delete[] this->text;
	this->text = new char[(this->laenge + op.laenge)+1];
	int zaehler=0;
	for(int i = 0 ; i < this->laenge ; i++)
	{
		this->text[i] = this->zwischenspeicher[i];

		zaehler++;
	}

	int zaehler2=0;
	for(int i = zaehler ; i < (this->laenge + op.laenge) ; i++)
	{
		this->text[i] = op.text[zaehler2];
		zaehler2++;
		index = i;
	}

	this->text[index+1] = '\0';
	this->laenge = (this->laenge + op.laenge);

	return *this;
}

String& String::operator=(String& op){
		if(this != &op)
	{
		delete[] this->text;
		delete[] this->zwischenspeicher;

		this->text = new char[op.laenge+1];
		this->zwischenspeicher = new char[0];
		this->laenge = op.laenge;

		for(int i = 0 ; i <= op.laenge ; i++)
		{
			this->text[i] = op.getText(i);
		}

	}
	return *this;
}
char& String::operator[](int index)
{
	return this->text[index];
}
ostream& operator<<(ostream& out,String& op){

	for(int i = 0 ; i < op.getLaenge() ; i++)
	{
		out<<op[i];
	}
	return out;
}

int String::getLaenge()
{
	return this->laenge;
}
